package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import searcher.DocSearcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: HUAWEI
 * Date: 2023-09-08
 * Time: 20:21
 */
public class DocSearcherServlet  extends HttpServlet {
    //调用实例，全局唯一，可以加上static
    private  static DocSearcher docSearcher = new DocSearcher();
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.先解析请求，拿到用户提交的查询词
        String query = req.getParameter("query");
        if(query == null || query == "") {
            String msg = "您的参数非法！没有获取到query的值！";
            System.out.println(msg);
            resp.sendError(40,msg);
            return;
        }
        //2.打印记录一下query的值
        System.out.println("query=" + query);
        //3.调用搜索模块来进行搜索
        List<Result> results  = docSearcher.search(query);
        //4.把当前的搜索结果进行打包；
        resp.setContentType("application/json;charset=utf-8");
        objectMapper.writeValue(resp.getWriter(),results);
    }
}